package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.PlaceAdapter;
import com.example.xianji.adapter.SkillAdapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.Place;
import com.example.xianji.bean.Skill;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;

public class Main_Skill_Activity extends Activity implements BGARefreshLayoutDelegate, OnClickListener {
    public static String text_skill_content = "";//记录技术页面去搜索的关键词
    public boolean skill_fenlei_flag = false;
    public String skill_fenlei_name = "选择分类";
    public int skill_fenlei_id = 0;
    /************************技术大厅**************************************/
    private BGARefreshLayout skill_RefreshLayout;
    private ListView skill_mylistview, skill_fenlei_liebiao;
    private SkillAdapter mSkill_Adapter;
    private ArrayList<Skill> list = new ArrayList<Skill>();
    private ArrayList<Place> skill_fenlei_list = new ArrayList<Place>();
    private ImageView skill_search, skill_iamge_load;
    private RelativeLayout skill_back;
    private int page = 1;
    private LinearLayout layout1, linear_layout_skill_fenlei;
    private PopupWindow show_popupWindow;
    private ListView show_listview;
    private PlaceAdapter mPlaceAdapter;
    private TextView text_skill_fenlei, text_skill_title;
    //    private SharedPreferences sp;
//    private Editor ed;
    private View translation_view;
    private AnimationDrawable skill_animation;
    private boolean isShowing = false;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                skill_animation.stop();
                skill_iamge_load.setVisibility(View.GONE);
                skill_mylistview.setAdapter(mSkill_Adapter);
                skill_RefreshLayout.endRefreshing();
            }
            if (msg.what == 2) {
                mSkill_Adapter.notifyDataSetChanged();
                skill_RefreshLayout.endLoadingMore();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__skill_);

        //	XJApplication.getInstance3().addActivity3(this);

        skill_back = (RelativeLayout) findViewById(R.id.skill_relative_back);

        skill_RefreshLayout = (BGARefreshLayout) findViewById(R.id.skill_RefreshLayout);
        skill_mylistview = (ListView) findViewById(R.id.skill_mylistview);
        mSkill_Adapter = new SkillAdapter(Main_Skill_Activity.this, list);
        linear_layout_skill_fenlei = (LinearLayout) findViewById(R.id.linear_layout_skill_fenlei);
        skill_search = (ImageView) findViewById(R.id.skill_search);
        text_skill_fenlei = (TextView) findViewById(R.id.text_skill_fenlei);
        text_skill_title = (TextView) findViewById(R.id.text_skill_title);
        skill_fenlei_liebiao = (ListView) findViewById(R.id.skill_fenlei_liebiao);
        skill_iamge_load = (ImageView) findViewById(R.id.skill_iamge_load);
        translation_view = findViewById(R.id.translation_view);

        skill_animation = (AnimationDrawable) skill_iamge_load.getDrawable();
        skill_animation.start();
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();

        if (text_skill_content.length() > 0) {
            text_skill_title.setText(text_skill_content);
        } else {
            text_skill_title.setText("技术大厅");
        }
        text_skill_fenlei.setText(skill_fenlei_name);
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_skill_data();
            }
        });
        skill_RefreshLayout.setDelegate(this);
        skill_back.setOnClickListener(this);
        skill_search.setOnClickListener(this);
        linear_layout_skill_fenlei.setOnClickListener(this);
        processLogic(savedInstanceState);
    }

    protected void processLogic(Bundle savedInstanceState) {
        skill_RefreshLayout.setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(this, true));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.skill_relative_back) {
            Main_Skill_Activity.this.finish();
        } else if (v.getId() == R.id.skill_search) {
            Intent intent = new Intent(Main_Skill_Activity.this, Main_SearchActivity.class);
            intent.putExtra("search", 4);
            startActivity(intent);
        } else if (v.getId() == R.id.linear_layout_skill_fenlei) {
            mPlaceAdapter = new PlaceAdapter(this, skill_fenlei_list, 2);
            show();
            skill_fenlei_liebiao.setAdapter(mPlaceAdapter);
            skill_fenlei_liebiao.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    hide();
                    text_skill_fenlei.setText(skill_fenlei_list.get(arg2).getArea_name());
                    if (skill_fenlei_list.get(arg2).getArea_name().equals("军民融合")) {
                        Main_Skill_Activity.this.startActivity(new Intent(Main_Skill_Activity.this, Main_JunMing_RongHeActivity.class));
                    } else {
                        skill_fenlei_name = skill_fenlei_list.get(arg2).getArea_name();
                        skill_fenlei_id = Integer.parseInt(skill_fenlei_list.get(arg2).getArea_id());
                        skill_fenlei_flag = true;
                        get_skill_data();
                    }
                }
            });
            translation_view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    hide();
                }
            });
        }
    }

    private boolean show() {
        skill_fenlei_liebiao.setVisibility(View.VISIBLE);
        translation_view.setVisibility(View.VISIBLE);
        isShowing = true;
        return isShowing;
    }

    protected boolean hide() {
        skill_fenlei_liebiao.setVisibility(View.GONE);
        translation_view.setVisibility(View.GONE);
        isShowing = false;
        return isShowing;
    }

    public void get_skill_data() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("page", 1 + "");
        map.put("cid", skill_fenlei_id + "");
        map.put("k", text_skill_content);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.skill,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        JSONArray ay = array.getJSONArray(0);
                        JSONArray ay1 = array.getJSONArray(1);
                        if (ay.length() > 0) {
                            for (int i = 0; i < ay.length(); i++) {
                                JSONObject object = ay.getJSONObject(i);
                                Skill mSkill = new Skill();
                                mSkill.setTitle(object.getString("title"));
                                mSkill.setName(object.getJSONObject("parents").getString("name"));
                                mSkill.setId(object.getString("id"));
                                list.add(mSkill);
                            }
                        } else {
                            Toast.makeText(Main_Skill_Activity.this, "暂无数据", Toast.LENGTH_LONG).show();
                        }
                        skill_fenlei_list.clear();
                        Place mPlace1 = new Place();
                        mPlace1.setArea_id("1");
                        mPlace1.setArea_name("军民融合");
                        skill_fenlei_list.add(mPlace1);
                        for (int i = 0; i < ay1.length(); i++) {
                            JSONObject object1 = ay1.getJSONObject(i);
                            Place mPlace = new Place();
                            mPlace.setArea_id(object1.getInt("id") + "");
                            mPlace.setArea_name(object1.getString("name"));
                            skill_fenlei_list.add(mPlace);
                        }
                        handler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                skill_RefreshLayout.endRefreshing();
                skill_animation.stop();
                skill_iamge_load.setVisibility(View.GONE);
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_skill_data_more() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("page", page + "");
        if (skill_fenlei_flag) {
            map.put("cid", skill_fenlei_id + "");
        }
        map.put("k", text_skill_content);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.skill,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        JSONArray ay = array.getJSONArray(0);
                        if (ay.length() > 0) {
                            for (int i = 0; i < ay.length(); i++) {
                                JSONObject object = ay.getJSONObject(i);
                                Skill mSkill = new Skill();
                                mSkill.setTitle(object.getString("title"));
                                mSkill.setName(object.getJSONObject("parents").getString("name"));
                                mSkill.setId(object.getString("id"));
                                list.add(mSkill);
                            }
                        } else {
                            Toast.makeText(Main_Skill_Activity.this, "没有更多数据", Toast.LENGTH_LONG).show();
                        }
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                skill_RefreshLayout.endLoadingMore();
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void province_Photo_show() {
        layout1 = (LinearLayout) LayoutInflater.from(
                Main_Skill_Activity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout1.findViewById(R.id.information_photo_listview);
        show_popupWindow = new PopupWindow(layout1, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.AnimTopMiddle);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout1);
        show_popupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (text_skill_content.length() > 0) {
            text_skill_title.setText(text_skill_content);
        } else {
            text_skill_title.setText("技术大厅");
        }
        if (Main_SearchActivity.skill_search_id == 1) {
            XJApplication.cachThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    get_skill_data();
                }
            });
            Main_SearchActivity.skill_search_id = 0;
        }
        skill_RefreshLayout.endRefreshing();
        skill_RefreshLayout.endLoadingMore();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                page = 1;
                get_skill_data();
            }
        });
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                page++;
                get_skill_data_more();
            }
        });
        return true;
    }

    @Override
    public void onBackPressed() {
        if (isShowing) {
            hide();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        text_skill_content = "";
    }
}
